const db = wx.cloud.database();
Page({
  data: {
    records: [],
    totalCount: 3,
    averageScore: 0,
  },
  goBack() {
    wx.navigateBack();
  },


  onLoad: function(options) {
    const openid = options.openid; 
    console.log('Received openid:', openid);
    this.getRecord(openid);
  },

  getRecord: function(openid) {
    db.collection('answer_record').where({
      openid: openid  
    }).get().then(res => {
      this.setData({
        records: res.data,
      });
      this.calculateAverageScore();
    })
  },

  nextPage:function(e){
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../../experience/answer_record/answer_record?_id=${id}`,
    })
  },

  detele: function (e) {
    const id = e.currentTarget.dataset.id; 

    wx.showModal({
      title: '确认删除',
      content: '您确定要删除这条记录吗？',
      success: (res) => {
        if (res.confirm) {
          db.collection('answer_record').doc(id).remove()
            .then(res => {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              this.getRecord(); // 重新加载记录
            })
            .catch(err => {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
              console.error('删除记录失败:', err);
            });
        }
      }
    });
  },

  calculateAverageScore: function() {
    const { records } = this.data;
    if (records.length === 0) {
      this.setData({ averageScore: 0 }); // 如果没有记录，平均分为 0
      return;
    }
    const totalScore = records.reduce((sum, record) => sum + record.totalScore, 0);
    const averageScore = (totalScore / records.length).toFixed(2); // 保留两位小数
    this.setData({ averageScore }); // 更新平均得分
  },

});
